<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchParam.supplierId"
            placeholder="请选择供应商"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in partnerList"
              :key="item.id"
              :label="item.partnerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchParam.dateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            @change="getplanDate"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button type="primary" plain :disabled="ids.length === 0"
          >打印发货单</el-button
        > -->
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="delParam()"
          ><i-ep-delete />删除</el-button
        >
        <el-button
          type="primary"
          plain
          :disabled="ids.length === 0"
          @click="deliveryParam()"
          >发货</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="发货单号"
          prop="exteriorDeliveryCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="承运商"
          prop="generalCarrierCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="车牌号"
          prop="vehicleCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="司机"
          prop="driverName"
          min-width="80"
          show-overflow-tooltip
        />
        <el-table-column
          label="状态"
          prop="enabled"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.deliveryState === 1"
              >已发货</el-tag
            >
            <el-tag type="info" v-else>待发货</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="联系电话"
          prop="driverPhone"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="车型"
          prop="vehicleTypeName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="交货地"
          prop="destinationDescription"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="发货时间"
          prop="sendingTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-dropdown size="small">
              <el-button type="primary" size="small" style="width: 75px">
                更多菜单
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogdetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="scope.row.deliveryState === 0"
                    @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item @click="open(scope.row)"
                    >打印</el-dropdown-item
                  >
                  <el-dropdown-item @click="unitPrint(scope.row)"
                    >包装打印</el-dropdown-item
                  >

                  <el-dropdown-item
                    v-if="scope.row.deliveryState === 0"
                    @click="handleTableDelete(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesExteriorDelivery-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <div id="printBox" v-if="isPrint" style="opacity: 0">
      <div
        style="margin-bottom: 20px"
        v-for="item in printData"
        :key="item?.id"
      >
        <div :id="`printId_${item?.id || ''}`">
          <span style="font-size: 15px; font-weight: 100; margin-right: 20px"
            >表单编码：DKIA-SCM-033</span
          >

          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span
            style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >大连施奈莱克创新零部件有限公司</span
          >
          &nbsp;&nbsp;<span
            style="font-size: 20px; font-weight: 100; margin-right: 20px"
            >委外加工出库单</span
          >
          <br /><br />
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >供应商名称：</span
          ><span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            ><input type="checkbox" id="checkbox1" /> 大连永光</span
          >&nbsp;&nbsp;<span
            style="font-size: 18px; font-weight: 100; margin-right: 20px"
            ><input type="checkbox" id="checkbox1" /> 宽世电泳</span
          >&nbsp;&nbsp;<span
            style="font-size: 18px; font-weight: 100; margin-right: 20px"
            ><input type="checkbox" id="checkbox1" /> 宏升电泳</span
          >&nbsp;&nbsp;<span
            style="font-size: 18px; font-weight: 100; margin-right: 20px"
            ><input type="checkbox" id="checkbox1" /> 永光表面处理</span
          >&nbsp;&nbsp;<span
            style="font-size: 18px; font-weight: 100; margin-right: 20px"
            ><input type="checkbox" id="checkbox1" /> 其它</span
          >
          <br />
          <br />
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >订单号： {{ item?.exteriorDeliveryCode || "&nbsp;" }}</span
          >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >单据号</span
          >

          <table cellpadding="0" cellspacing="0">
            <tr>
              <td>
                <table
                  border="1"
                  cellpadding="5"
                  cellspacing="0"
                  width="800px"
                  style="height: 450px"
                >
                  <thead>
                    <tr>
                      <th rowspan="2">存货名称</th>
                      <th rowspan="2">规格型号</th>
                      <th rowspan="2">存货编码</th>
                      <th rowspan="2">单位</th>
                      <th colspan="2">数量</th>
                      <th style="width: 200px" rowspan="2">备注</th>
                    </tr>
                    <tr>
                      <th>请领</th>
                      <th>实发</th>
                    </tr>
                  </thead>
                  <tbody align="center">
                    <tr
                      v-for="(i, index) in item?.mesProduceTransferFormDTOSSum"
                      :key="index"
                    >
                      <td>{{ i?.figureNumber || "&nbsp;" }}</td>
                      <td>{{ i?.remarks || "&nbsp;" }}</td>
                      <td>
                        {{
                          (i?.materialCode || "&nbsp;") +
                          (i?.shiftName ? "  " + i?.shiftName : "")
                        }}
                      </td>
                      <td>
                        {{ i?.unitName || "&nbsp;" }}
                      </td>
                      <td>{{ i?.productQuantity || "&nbsp;" }}</td>
                      <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                      <td></td>
                    </tr>
                    <tr>
                      <td
                        colspan="7"
                        style="text-align: left; font-weight: bold"
                      >
                        合计
                      </td>
                    </tr>
                  </tbody>
                </table>
              </td>
              <td>
                <table
                  border="1"
                  cellpadding="5"
                  cellspacing="0"
                  width="150px"
                  style="height: 450px"
                >
                  <tr>
                    <td style="border-left: none">第一联存根</td>
                    <td style="border-left: 2px solid black">第二联财务</td>
                    <td style="border-left: 2px solid black">第三联仓库</td>
                    <td style="border-left: 2px solid black">第四联供应商</td>
                    <td style="border-left: 2px solid black">第五联出门票</td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >领料</span
          >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >发料</span
          >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
            >发料部门主管</span
          ><br />
          <img
            style="
              width: 70px;
              display: flex;
              align-items: center;
              margin-left: 880px;
              margin-top: -560px; /* 向上移动 */
            "
            src="http://192.168.3.6:8030/assets/logo-icon-93e3e252.png"
          />
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
        <div style="margin-top: 500px; text-align: center">
          <div style="display: flex; justify-content: center; gap: 10px">
            <!--          <el-button size="small" @click="getPrintData()">打印</el-button>
          <el-button size="small" @click="close()">返回</el-button>-->
          </div>
        </div>
      </div>
    </div>
    <!-- 打印包装 -->
    <div id="printBoxUnit" v-if="isPrint" style="opacity: 0">
      <div
        style="margin-bottom: 20px"
        v-for="item in printDataUnit"
        :key="item?.id"
      >
        <div
          :id="`printId_${item?.id || ''}`"
          style="width: 394px; height: 394px"
        >
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <canvas :id="`barcode_${item?.id || ''}`"></canvas> -->
          <div
            style="
              font-size: 12px;
              font-weight: 600;
              word-break: break-all;
              width: 390px;
            "
          >
            <span style="font-size: 18px; font-weight: 100; margin-right: 20px"
              ><text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.externalCode || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >存货编码：&nbsp;<text
                style="font-size: 20px; font-weight: 600; margin-right: 20px"
                >{{ item?.materialCode || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >材质：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.materialQuality || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >规格型号：&nbsp;<text
                style="font-size: 20px; font-weight: 600"
                >{{ item?.materialSpecification || "" }}</text
              ></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: -10px; width: 390px">
            <br />
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >图号：&nbsp;<text style="font-size: 20px; font-weight: 600">{{
                item?.figureNumber || ""
              }}</text></span
            >
          </div>
          <div style="font-size: 14px; margin-bottom: 0px; width: 390px">
            <br /><span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 10px;
                font-weight: 600;
              "
              >生产批次：<text
                style="font-size: 20px; font-weight: 600; margin-right: 10px"
                >{{ item?.remarks || "" }}</text
              ></span
            >
            <span
              style="
                font-size: 18px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >数量：&nbsp;<text style="font-size: 20px; font-weight: 600"
                >{{ item?.productQuantity || "" }}
                {{ item?.unitName || "" }}</text
              >
            </span>
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 12px; width: 390px; margin-bottom: 1px">
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印时间：&nbsp;<text>{{ item?.createTime || "" }}</text></span
            >
            <span
              style="
                font-size: 12px;
                font-weight: 100;
                margin-right: 20px;
                font-weight: 600;
              "
              >打印人：&nbsp;<text
                >{{ item?.createdUserName || "" }}&nbsp;</text
              ></span
            >
          </div>
          <div style="height: 5px"></div>
          <div style="font-size: 14px; width: 400px; display: flex">
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者1：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >操作者2：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
            <span
              style="
                flex: 1;
                font-weight: 100;
                font-size: 14px;
                margin-right: 20px;
                font-weight: 600;
              "
              >检&nbsp;查：&nbsp;&nbsp;&nbsp;&nbsp;</span
            >
          </div>
          <div
            style="
              font-size: 17px;
              margin-bottom: 0px;
              width: 300px;
              font-weight: 600;
            "
          ></div>
        </div>
      </div>
      <div style="margin-top: 500px; text-align: center">
        <div style="display: flex; justify-content: center; gap: 10px">
          <!--        <el-button size="small" @click="getPrintData()">打印</el-button>
        <el-button size="small" @click="close()">返回</el-button>-->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTable } from "@/utils/useTable";
import request from "@/utils/request";
import { getSupplierList } from "@/utils/commonData";
import { getLodop } from "@/utils/LocalLodopFuncs";
import { RootObject } from "@/views/demo/iframePrintDelivery/index";
import { isWindow7 } from "@/utils/index";
defineOptions({
  name: "Mesexteriordelivery",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesexteriordelivery/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  supplierId: "",
  dateSearch: [],
  dateStart: "",
  dateEnd: "",
};

const deleteParam = {
  api: "/mes/mesexteriordelivery/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const partnerList: any = ref(); // 委外供应商/客户
onMounted(() => {
  getTableList();
  getPlantList();
  getPartnerList();
});
async function getPartnerList() {
  partnerList.value = (await getSupplierList("")) || [];
}
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesexteriordelivery/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开外协发货单表单弹窗 */
function openDialog(roleObj?: any) {
  if (roleObj) {
    addDialog.title = "修改发货单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "创建发货单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开外协发货单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "外协发货单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  getTableList();
  inputAutoFocus();
  if (!value) {
    addDialog.data = {};
  }
}

function getplanDate(data: any) {
  if (data) {
    searchParam.value.dateStart = data[0];
    searchParam.value.dateEnd = data[1];
  } else {
    searchParam.value.dateStart = "";
    searchParam.value.dateEnd = "";
  }
}

//工厂列表
const plantList: Ref<any> = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
};

// 批量删除接口
const delParam = async () => {
  ElMessageBox.confirm("确定批量删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesexteriordelivery/delete",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量删除成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 批量发货接口
const deliveryParam = async () => {
  ElMessageBox.confirm("确定批量发货吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesexteriordelivery/delivery",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量发货成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消发货",
      });
    });
};
// 进入页面聚焦
const inputRef = ref();
const readonly = ref(true);
const inputAutoFocus = () => {
  nextTick(() => {
    readonly.value = true;
    inputRef.value.focus();
    setTimeout(() => {
      readonly.value = false;
    }, 0);
  });
};

// 触发打印
const IFRAME_URL = import.meta.env.VITE_APP_IFRAME_URL;
const showWebView = ref(false);
const webviewSrc = ref("");
const returnText = ref("");
function confirmImport(id: string, instance: any, done: Function) {
  returnText.value = "";
  webviewSrc.value = `${IFRAME_URL}iframePrintDelivery?id=${id}`;
  console.log("webviewSrc.value", webviewSrc.value);
  showWebView.value = true;
  // 设置调用间隔，当打印机被初始化后，提醒用户打印中
  let sumTime = 0;
  let intervalId = setInterval((instance1 = instance, done1 = done) => {
    sumTime += 500;
    if (returnText.value.length) {
      instance1.confirmButtonLoading = false;
      showWebView.value = false;
      done1();
      ElMessage(returnText.value);
      clearInterval(intervalId);
    }
    if (sumTime >= 5000 && !returnText.value) {
      instance1.confirmButtonLoading = false;
      showWebView.value = false;
      done1();
      ElMessage.error("打印失败，请稍后再试");
      clearInterval(intervalId);
    }
  }, 500);
}
const open = (row) => {
  ElMessageBox.confirm(`请确认是否打印？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        // 开启按钮加载
        instance.confirmButtonLoading = true;
        // 调用打印页面
        // 跳转到指定页面
        insertOperateLog(row.id);
        // window.location.href = `${IFRAME_URL}iframePrintDelivery?id=${row.id}`;
        isPrint.value = true;
        printId.value = row.id;
        getPrintData();
        done();
      } else {
        done();
      }
    },
  }).catch(() => {});
};
//包装打印
const unitPrint = (row) => {
  ElMessageBox.confirm(`请确认是否打印？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        // 开启按钮加载
        instance.confirmButtonLoading = true;
        // 打印预览跳转到指定页面
        insertOperateLog(row.id);
        // window.location.href = `${IFRAME_URL}iframePrintDeliveryUnit?id=${row.id}`;
        // window.location.href = `http://localhost:3000/#/IframePrintDeliveryUnit?id=${row.id}`;
        // confirmImport(row.id, instance, done);
        isPrint.value = true;
        printId.value = row.id;
        getPrintDataUnit();
        done();
      } else {
        done();
      }
    },
  }).catch(() => {});
};
//打印日志信息
const operateLog = ref({
  logLevel: "INFO",
  applicationName: "jcfk-mes",
  modular: "外协发货开始",
  businessType: "打印",
  info: "",
});
//开始打印
async function insertOperateLog(id: any) {
  operateLog.value.info = id;
  await request({
    method: "POST",
    url: "/system/sysOperateLog/insert",
    data: operateLog.value,
  });
}
function handleIframeMessage(event) {
  // 获取从 Vue 组件发送过来的数据
  const receivedData = event.data;
  returnText.value = receivedData;
  // 在这里处理接收到的数据
  console.log("receivedData", receivedData); // 输出传输过来的数据
}

onMounted(() => {
  getTableList();
  inputAutoFocus();
  // 添加iframe监听
  window.addEventListener("message", handleIframeMessage);
});

onBeforeUnmount(() => {
  // 销毁iframe监听
  window.removeEventListener("message", handleIframeMessage);
});
const isPrint = ref(false);
let printId = ref("");
// 打印数据，数组形式
const printData = ref<RootObject[]>([]);
const window7 = ref(false);
// 获取打印数据
async function getPrintData() {
  const { data } = await request({
    url: `/mes/mesexteriordelivery/getprint/${printId.value}`,
    method: "get",
    data: {},
  }).finally(() => {});
  console.log(data.mesProduceTransferFormDTOS);
  //printData.value = data.mesProduceTransferFormDTOS; //多张打印
  printData.value = data; //单张打印
  window7.value = isWindow7();
  nextTick(() => {
    printData.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);

      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(qrCodeElement, e.exteriorDeliveryCode || "", {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          });
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`包装打印-${printId.value}`);
    // LODOP.SET_LICENSES(
    //   defaultSettings.printCompany,
    //   defaultSettings.printLicenses,
    //   "",
    //   ""
    // );
    printData.value?.map((e) => {
      printFun(e, LODOP);
    });
    //LODOP.PRINT(); // 打印
    isPrint.value = false;
    LODOP.PREVIEW(); // 预览
    window.parent.postMessage("打印中，请稍后...", "*");
    insertOperateLog(printId.value);
  }, 1000);
}

function printFun(pitem: any, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(2, "297mm", "210mm", "A4"); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    10,
    10,
    "200mm",
    "180mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "160mm",
    "10mm",
    "25mm",
    "25mm",
    "QRCode",
    pitem?.exteriorDeliveryCode || ""
  );
  LODOP.ADD_PRINT_TEXT(700, 23, 98, 500, "委外加工出库单");
  LODOP.ADD_PRINT_LINE("19mm", "190mm", "19mm", "230mm", 0, 1);
  //打印预览false纵向
  LODOP.SET_SHOW_MODE("LANDSCAPE_DEFROTATED", true);
  LODOP.NEWPAGE(); //另起一页
}
const printDataUnit = ref<RootObject[]>([]);
// 包装打印--获取打印数据
async function getPrintDataUnit() {
  const { data } = await request({
    url: `/mes/mesexteriordelivery/getprintunits/${printId.value}`,
    method: "get",
    data: {},
  }).finally(() => {});
  //printDataUnit.value = [data, data, data]; //多张打印
  printDataUnit.value = data; //单张打印

  nextTick(() => {
    printDataUnit.value?.map(async (e) => {
      const qrCodeId = `barcode_${e?.id || ""}`;
      const qrCodeElement = document.getElementById(qrCodeId);

      if (qrCodeElement) {
        try {
          await QRCode.toCanvas(qrCodeElement, e.externalCode || "", {
            width: 100, // 可以根据需要调整二维码的大小
            margin: 1, // 可以根据需要调整二维码的边距
          });
        } catch (err) {
          console.error("Error generating QR code:", err);
        }
      }
    });
  });
  setTimeout(() => {
    let LODOP = getLodop();
    LODOP.PRINT_INIT(`包装打印-${printId.value}`);
    // LODOP.SET_LICENSES(
    //   defaultSettings.printCompany,
    //   defaultSettings.printLicenses,
    //   "",
    //   ""
    // );
    printDataUnit.value?.map((e) => {
      printFunUnit(e, LODOP);
    });
    //LODOP.SET_PRINTER_INDEX("ZDesigner ZT231-203dpi ZPL");
    //LODOP.PRINT(); // 打印
    console.log(LODOP.Printers.list);
    LODOP.PREVIEW(); // 预览
    isPrint.value = false;
    window.parent.postMessage("打印中，请稍后...", "*");
    insertOperateLog(printId.value);
  }, 1000);
}
function printFunUnit(pitem: any, LODOP: any) {
  LODOP.SET_PRINT_PAGESIZE(1, "100mm", "100mm", ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  //LODOP.ADD_PRINT_RECT(0, 5, 310, 220, 0, 1); //边框设置：上、左、宽、高、线条：0实线 1虚线
  //LODOP.SET_PRINT_STYLE("FontSize", 7.5);
  //LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.ADD_PRINT_HTM(
    "40mm",
    "10mm",
    "100mm",
    "100mm",
    document.getElementById(`printId_${pitem?.id || ""}`)?.innerHTML
  );
  LODOP.ADD_PRINT_BARCODE(
    "5mm",
    "30mm",
    "40mm",
    "40mm",
    "QRCode",
    pitem?.externalCode || ""
  );
  LODOP.NEWPAGE(); //另起一页
}
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
